import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ParseCourse {
    public void parse(){
        try {
            parse(new File("data.json"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void parse(File data_file) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(data_file)));
        StringBuilder sb = new StringBuilder();
        String str;
        while((str=br.readLine())!=null){
            sb.append(str);
        }
        JSONObject data = JSONObject.parseObject(sb.toString()).getJSONObject("data");
        int course_id = data.getJSONObject("info").getIntValue("id");
        JSONArray course_list = data.getJSONArray("list");
        URL_utils u = new URL_utils();
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i=0;i<course_list.size();i++){
            JSONObject course = course_list.getJSONObject(i);
            JSONArray child = course.getJSONArray("child");
            String course_title = course.getString("title");
            for(int j=0;j<child.size();j++) {
                int video_id = child.getJSONObject(j).getIntValue("video_id");
                if (video_id > 0) {
                    String chapter_title = child.getJSONObject(j).getString("periods_title");
                    if(!chapter_title.endsWith(".mp4")) chapter_title += ".mp4";
                    System.out.println("将要下载视频 " + video_id);
                    String finalChapter_title = chapter_title;

                    if(child.size()>1) {
                        threadPool.execute(() -> u.download_video(video_id, course_id, String.format("download/%s/%s", course_title, finalChapter_title)));
                    }else {
                        threadPool.execute(() -> u.download_video(video_id, course_id, String.format("download/%s", finalChapter_title)));
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        ParseCourse pc = new ParseCourse();
        pc.parse();
    }
}
